package com.app.twth.ui.finalprocess;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityFinalprocessBinding;
import com.app.twth.databinding.DialogFinalprocessDetailBinding;
import com.app.twth.ui.finalprocess.lpn.FinalProcessLpnActivity;
import com.app.twth.ui.finalprocess.rp.FinalProcessRPActivity;
import com.app.twth.ui.finalprocess.submit.FinalProcessSubmitActivity;
import com.app.twth.utils.DividerItemDecoration;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class FinalProcessActivity extends BaseActivity<ActivityFinalprocessBinding, FinalProcessViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type;
    private List<String> batchList = null;
    private FinalProcessAdapter adapter;

    @Override
    protected void initListener() {
        viewModel.finalProcessLiveData.observe(this, data -> {
            FinalProcess.ItemInfoDTO itemInfo = data.getItemInfo();
            if (itemInfo != null) {//trk
                Log.e(TAG, "itemInfo != null");
                setNext(itemInfo);
                return;
            }
            ArrayList<String> lpns = data.getIbLpnList();
            Bundle bundle = new Bundle();
            bundle.putString("batchNo", barcodeStr);
            bundle.putStringArrayList("list", lpns);
            AppRouter.showActivityForResult(mContext, FinalProcessLpnActivity.class, bundle, Constant.ForResult2);
        });
        viewModel.batchDetailLiveData.observe(this, data -> {
            showTallyDetailDialog(data);
        });
        viewModel.batchListLiveData.observe(this, code -> {
            switch (type) {
                case 0:
                    batchList = viewModel.batchListLiveData.getValue().getPendingBatchList();
                    break;
                case 1:
                    batchList = viewModel.batchListLiveData.getValue().getCompletedBatchList();
                    break;
            }
            if (batchList == null) {
                batchList = new ArrayList<>();
            }
            adapter.setData(batchList, type);
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "FinalProcess";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);

        adapter = new FinalProcessAdapter(this, batchList, position -> {
            if (type == 1) {
                return;
            }
            if (batchList.size() <= position) {
                return;
            }
            barcodeStr = batchList.get(position);
            viewModel.returnFinalProcessCheckBatchNo(barcodeStr);
        }, position -> {
            if (batchList.size() <= position) {
                return;
            }
            barcodeStr = batchList.get(position);
            viewModel.returnFinalProcessDetail(barcodeStr);
        });
        binding.recyclerview.setHasFixedSize(true);
        binding.recyclerview.setItemAnimator(new DefaultItemAnimator());

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        //添加装饰类
        binding.recyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        binding.recyclerview.setAdapter(adapter);
        binding.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (batchList == null) {
                    batchList = new ArrayList<>();
                }
                batchList.clear();
                adapter.setData(batchList, type);

                if (viewModel.batchListLiveData.getValue() == null) {
                    viewModel.returnFinalProcessBatchList();
                    return;
                }
                switch (checkedId) {
                    case R.id.tv_tallying_list:
                        type = 0;
                        batchList = viewModel.batchListLiveData.getValue().getPendingBatchList();
                        break;
                    case R.id.tv_completed_list:
                        type = 1;
                        batchList = viewModel.batchListLiveData.getValue().getCompletedBatchList();
                        break;
                }
                if (batchList == null || batchList.size() == 0) {
                    viewModel.returnFinalProcessBatchList();
                    return;
                }
                adapter.setData(batchList, type);

            }
        });

        viewModel.returnFinalProcessBatchList();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }


    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                binding.tvCode.setText("");
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                barcodeStr = binding.tvCode.getText().toString();
                if (Utils.isEmpty(barcodeStr)) {
                    ToastUtil.showToast("Please enter batch #");
                    return;
                }
                viewModel.returnFinalProcessCheckBatchNo(barcodeStr);
                break;
        }
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                EditTextUtil.hideInput(mContext);

                if (Utils.isEmpty(barcodeStr)) {
                    return false;
                }
                viewModel.returnFinalProcessCheckBatchNo(barcodeStr);
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        binding.tvCode.setText(barcodeStr);
        viewModel.returnFinalProcessCheckBatchNo(barcodeStr);
    }

    private AlertDialog dialogDetail;

    private void showTallyDetailDialog(List<FinalProcessDetail> data) {
        dialogDetail = MyDialogUtil.getDialog(mContext, initDetailDialogView(data), Gravity.CENTER);
        dialogDetail.setCanceledOnTouchOutside(true);
        dialogDetail.show();
    }

    FinalProcessDetailAdapter tallyDetailAdapter;

    private View initDetailDialogView(List<FinalProcessDetail> data) {
        DialogFinalprocessDetailBinding dialogBinding = DialogFinalprocessDetailBinding.inflate(getLayoutInflater());

        dialogBinding.tvTitle.setText("Detail(" + barcodeStr + ")");
        dialogBinding.viewLine.setVisibility(View.GONE);
        dialogBinding.tvConfirm.setVisibility(View.GONE);
        dialogBinding.tvCancel.setText("Close");

        tallyDetailAdapter = new FinalProcessDetailAdapter(this, data);

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerviewDetail.setLayoutManager(layoutManager1);
        dialogBinding.recyclerviewDetail.setAdapter(tallyDetailAdapter);

        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogDetail != null) {
                dialogDetail.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }

    private void setNext(FinalProcess.ItemInfoDTO itemInfo) {
        FinalProcessQr finalProcessQr = new FinalProcessQr();
        finalProcessQr.setBatchNo(itemInfo.getBatchNo());
        finalProcessQr.setOldIbLpn(itemInfo.getIbLpn());
        finalProcessQr.setId(itemInfo.getId() + "");
        finalProcessQr.setTrackingCode(itemInfo.getTrackingCode());
        finalProcessQr.setType(itemInfo.getType());
        finalProcessQr.setSku(itemInfo.getSku());
        finalProcessQr.setNewSku(itemInfo.getNewSku());
        finalProcessQr.setQty(itemInfo.getQty());
        finalProcessQr.setOpenLassSku(itemInfo.getOpenLassSku());
        finalProcessQr.setAccountId(itemInfo.getAccountId());

        if (itemInfo.getType() == 4) {//重新拍照
            Bundle bundle = new Bundle();
            bundle.putSerializable("FinalProcessQr", finalProcessQr);
            AppRouter.showActivityForResult(mContext, FinalProcessRPActivity.class, bundle, Constant.ForResult2);
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putSerializable("FinalProcessQr", finalProcessQr);
        AppRouter.showActivityForResult(mContext, FinalProcessSubmitActivity.class, bundle, Constant.ForResult2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2) {
            viewModel.returnFinalProcessBatchList();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
